import axios from 'axios';
let iview = gMain.components.iView;
const serive = axios.create({
    baseURL:gMain.apiPath,
    timeout: 5000,
    method: "post",
    responseType: "json",
    contentType: "application/json;charset=UTF-8",
});
//添加请求拦截器
serive.interceptors.request.use(function(config){
    // 在发送请求之前做些什么
    // 请求数据防xss攻击处理
    if (typeof config.contentType !== 'boolean' && config.data) {
        var newData = "";
        var sType = typeof config.data;
        if (sType === "string") {
          newData = config.data;
        } else {
          newData = JSON.stringify(config.data);
        }
        newData = newData.replace(/<script/igm, "&lt;script").replace(/<\/script>/igm, "&lt;/script&gt;");
        if (sType === "string") {
            config.data = newData;
        } else {
            config.data = JSON.parse(newData);
        }
      }
      return config;
},function(error){
    // 对请求错误做些什么
    return Promise.reject(error);
});
// 添加响应拦截器
serive.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    let obj = response.data;
    if (obj) {
        var newData = "";
        var sType = typeof obj;
        if (sType === "string") {
          newData = obj;
        } else {
          newData = JSON.stringify(obj);
        }
        newData = newData.replace(/<script/igm, "&lt;script").replace(/<\/script>/igm, "&lt;/script&gt;");
        if (sType === "string") {
          obj = newData;
        } else {
          obj = JSON.parse(newData);
        }
      }
      if (response.config.dataType == "html") {
        obj = JSON.parse(obj);
      }
      //如果后端返回的错误统一拦截提示
      if (obj.result == "false" && !response.config.isPassFalse) {
        obj.resultDesc && iview.Message.error(
          {background: true
            ,content: obj.resultDesc
          }); //给个错误提示
      }
      response.data = obj;
    return response;
  }, function (error) {
    // 对响应错误做点什么
    if (error.request.readyState == 4) {
        iview.Message.error({background: true,content: '请求出错，请重试'});
    }
    return Promise.reject(error);
  });
export default serive;